<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;
use think\exception\PDOException;
use Exception;
use think\Db;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Product extends Backend
{

    /**
     * Product模型对象
     * @var \app\common\model\Product\Product
     */
    protected $model = null;

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    /**
     * 商品分类模型
     */
    protected $TypeModel = null;

    /**
     * 商品单位模型
     */
    protected $UnitModel = null;

    /**
     * 快速搜索
     */
    protected $searchFields = ['name', 'type.name', 'unit.name'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Product\Product;

        // 获取商品状态
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("StatusList", $this->model->getStatusList());
        $this->view->assign("RentStatusList", $this->model->getRentStatusList());

        // 商品分类模型
        $this->TypeModel = model('Product.Type');

        // 商品单位模型
        $this->UnitModel = model('Product.Unit');
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 商品列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        // 输出视图
        return $this->view->fetch();
    }

    /**
     * 添加商品
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');

            if (is_array($params) && !empty($params)) {
                $result = $this->model->validate('common/Product/Product')->save($params);

                if ($result === FALSE) {
                    // 从表单接收的图片
                    $thumbs = explode(',', $params['thumbs']);

                    $thumbs = array_filter($thumbs);

                    foreach ($thumbs as $value) {
                        if (!empty($value)) {
                            $thumb = ltrim($value, '/');

                            @is_file($thumb) && @unlink($thumb);
                        }
                    }

                    $this->error(__($this->model->getError()));
                } else {
                    $this->success();
                }
            }
        }

        $UnitData = $this->UnitModel->order('id', 'desc')->select();

        $UnitList = [];

        foreach ($UnitData as $item) {
            $UnitList[$item['id']] = $item['name'];
        }

        $TypeData = $this->TypeModel->order('id', 'desc')->select();

        $TypeList = [];

        foreach ($TypeData as $item) {
            $TypeList[$item['id']] = $item['name'];
        }

        $data = [
            'UnitList' => $UnitList,
            'TypeList' => $TypeList
        ];

        return $this->view->fetch('', $data);
    }

    /**
     * 编辑商品
     * 
     * @param String $ids 主键
     */
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);

        // 找不到数据返回错误信息
        if (!$row) {
            $this->error(__('该商品不存在，请重新选择'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');

            if (is_array($params) && !empty($params)) {
                $params['id'] = $ids;

                $result = $this->model->validate('common/Product/Product')->isUpdate(true)->save($params);

                if ($result === FALSE) {
                    // 从表单接收的图片
                    $thumbs = explode(',', $params['thumbs']);

                    // 当前的数据图片
                    $OldThumbs = explode(',', $row['thumbs']);

                    $thumbs = array_filter($thumbs);

                    foreach ($thumbs as $value) {
                        if (!in_array($value, $OldThumbs)) {
                            $thumb = ltrim($value, '/');

                            @is_file($thumb) && @unlink($thumb);
                        }
                    }

                    $this->error(__($this->model->getError()));
                } else {
                    // 从表单接收的图片
                    $thumbs = explode(',', $params['thumbs']);

                    // 当前的数据图片
                    $OldThumbs = explode(',', $row['thumbs']);

                    $thumbs = array_filter($thumbs);

                    foreach ($OldThumbs as $item) {
                        if (!in_array($item, $thumbs)) {
                            $thumb = ltrim($item, '/');

                            @is_file($thumb) && @unlink($thumb);
                        }
                    }

                    $this->success();
                }
            }
        }

        $UnitData = $this->UnitModel->order('id', 'desc')->select();

        $UnitList = [];

        foreach ($UnitData as $item) {
            $UnitList[$item['id']] = $item['name'];
        }

        $TypeData = $this->TypeModel->order('id', 'desc')->select();

        $TypeList = [];

        foreach ($TypeData as $item) {
            $TypeList[$item['id']] = $item['name'];
        }

        // 赋值给模板使用的变量
        $data = [
            'row' => $row,
            'UnitList' => $UnitList,
            'TypeList' => $TypeList
        ];

        return $this->view->fetch('', $data);
    }

    /**
     * 软删除
     * 
     * @param String $ids 主键
     */
    public function del($ids = null)
    {
        $list = $this->model->where(['id' => ['in', $ids]])->select();

        if (!$list) {
            $this->error(__('请选择需要删除的商品'));
        }

        $count = 0;

        // 开启事务
        Db::startTrans();

        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }

            // 提交事务
            Db::commit();
        } catch (PDOException | Exception $e) {
            // 事务回滚
            Db::rollback();

            // 获取错误信息
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
    }

    /**
     * 回收站
     */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->onlyTrashed()
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        // 输出视图
        return $this->view->fetch();
    }

    /**
     * 还原
     * 
     * @param str $ids 主键
     */
    public function restore($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->select();

            if (!$row) {
                $this->error(__('请选择需要还原的商品'));
            }

            $data = [];

            foreach ($row as $key => $item) {
                $data[] = [
                    'id' => $item['id'],
                    'deletetime' => null
                ];
            }

            $result = $this->model->isUpdate(true)->saveAll($data);

            if ($result === FALSE) {
                $this->error(__('还原失败'));
            } else {
                $this->success();
            }
        }
    }

    /**
     * 真实删除
     */
    public function destroy($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->select();

            if (!$row) {
                $this->error(__('请选择需要删除商品'));
            }

            $result = $this->model->destroy($ids, true);

            if ($result === FALSE) {
                $this->error(__('删除失败'));
            } else {

                // 遍历数据获取图片
                foreach ($row as $item) {
                    // 把thumbs字段的值转成数组
                    $thumbsArr = !empty($item['thumbs']) ? explode(',', $item['thumbs']) : [];

                    $thumbsArr = array_filter($thumbsArr);

                    foreach ($thumbsArr as $val) {
                        $thumb = ltrim($val, '/');

                        @is_file($thumb) && @unlink($thumb);
                    }
                }

                $this->success();
            }
        }
    }
}
